<link rel="stylesheet" href="static/plugins/ztree/zTreeStyle.css" type="text/css">
<style>
    ul.ztree {
        border: 1px solid #E6E6E6;
        border-top: none;
    }

    ul.ztree .node_name{
        font: 14px Helvetica Neue, Helvetica, PingFang SC, \5FAE\8F6F\96C5\9ED1, Tahoma, Arial, sans-serif;
    }
    ul.ztree li {
        margin: 8px 0;
    }

    .cate {
        border: 1px solid #E6E6E6;
        padding: 9px 0 9px 8px;
        background: #F2F2F2;
    }

    .cate-add, .cate-refresh, .cate-edit {
        float: right;
        margin-right: 8px;
        cursor: pointer;
    }

    .cate-parent {
        cursor: pointer;
    }

    .layui-table, .layui-table-view {
        margin: 0;
    }

    .layui-form-selected dl {
        height: 220px;
    }

    .ztree li span.button.ico_docu {
        margin-top: 2px;
    }

    .ztree li a {
        padding: 1px 3px 3px 0;
    }
</style>
<div style="float:left;width:15%;max-width: 250px;">
    <div class="cate">
        <span class="cate-parent"><img src="static/plugins/ztree/img/home.png"/> 分类栏目</span>
        <span class="cate-add"><img src="static/plugins/ztree/img/add.png"/></span>
        <span class="cate-refresh"><img src="static/plugins/ztree/img/refresh.png"/></span>
    </div>
    <ul id="zTree" class="ztree"></ul>
</div>
<div style="float:left;margin-left:5px;width:84.5%;height:700px;">
    <div id="cate-list" lay-filter="cate-list-blur"></div>
</div>
<script type="text/javascript" src="static/plugins/ztree/jquery.ztree.core.js"></script>
<!-- 添加与编辑分类-->
<div id="category-box" style="display: none">
    <form class="layui-form layui-form-pane" lay-filter="category" style="width: 350px;">
        <input type="hidden" id="model" name="model">
        <div style="padding: 10px;">
            <div class="layui-form-item">
                <label class="layui-form-label">父菜单</label>
                <div class="layui-input-block">
                    <select id="selPid" name="parentId" lay-verify="required"  lay-filter="selClick">
                        <!--<option id="pid_0" value="0">顶级菜单</option>-->
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">分类名称</label>
                <div class="layui-input-block">
                    <input type="text" name="catName" autocomplete="off" lay-verify="required|number"
                           placeholder="请输入分类名称" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">链接地址</label>
                <div class="layui-input-block">
                    <input type="text" name="linkUrl" autocomplete="off" placeholder="系统菜单默认可以不填" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label id="iconUpload" class="layui-form-label" style="cursor: pointer" index="0"><i class="layui-icon">&#xe62f;</i>
                    手机图标</label>
                <div class="layui-input-block">
                    <input type="text" id="appIcon" name="appIcon" autocomplete="off" placeholder="可以填写URL, 也可以通过上传"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label id="iconUpload" class="layui-form-label" style="cursor: pointer" index="1"><i class="layui-icon">&#xe62f;</i>
                    Web图标</label>
                <div class="layui-input-block">
                    <input type="text" id="webIcon" name="webIcon" autocomplete="off" placeholder="可以填写URL, 也可以通过上传"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">排序</label>
                <div class="layui-input-block">
                    <input type="text" name="sort" autocomplete="off" lay-verify="required|number" placeholder="请输入排序"
                           class="layui-input" style="width: 100px;float:left;">
                    <div id="isViewSwitch" style="float:right;">
                        <input type="checkbox" id="isView" name="isView" lay-skin="switch" lay-text="显示|隐藏"
                               lay-filter="isViewCheck" value="1" checked>
                    </div>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">描述</label>
                <div class="layui-input-block">
                    <textarea name="description" placeholder="请输入内容" class="layui-textarea"
                              style="min-height:30px;resize:none;"></textarea>
                </div>
            </div>

        </div>
    </form>
</div>
<script type="text/html" id="actBar">
    <a id="edit-cate" class="layui-btn layui-btn-primary layui-btn-xs" data="{{d.catId}}" cate="{{d.catName}}" option="1"><i
            class="layui-icon">&#xe642;</i>编辑</a>
    {{# if(d.isSys){}}
    <a class="layui-btn layui-btn-danger layui-btn-xs layui-btn-disabled"><i
            class="layui-icon">&#xe640;</i>删除</a>
    {{#}else{}}
    <a id="del-cate" class="layui-btn layui-btn-danger layui-btn-xs" data="{{d.catId}}" cate="{{d.catName}}" ><i
            class="layui-icon">&#xe640;</i>删除</a>
    {{#}}}

</script>
<script type="text/html" id="checkBar">
    <input type="checkbox" name="switch" cate="{{d.catName}}" value="{{d.catId}}" lay-skin="switch"
           lay-filter="viewCheck" lay-text="显示|隐藏" {{#
           if(d.isView){}}checked{{#}}}>
</script>
<script type="text/html" id="appIconBar">
    <img src="{{d.appIcon}}" onerror="this.src='static/icon/icon-default.svg'" style="width: 25px;height:25px;"/>
</script>
<script type="text/html" id="webIconBar">
    <img src="{{d.webIcon}}" onerror="this.src='static/icon/icon-default.svg'" style="width: 25px;height:25px;"/>
</script>
<script type="text/javascript">
    $(document).ready(function () {
        var zt, lastNode;
        var zTreeOnClick = function (event, treeId, node) {
            if (!node.isParent) {
                //zt.cancelSelectedNode(node);
                //zt.selectNode(lastNode);
            } else {
                renderTable(node.id);
                lastNode = node;
            }
        }

        var setting = {
            view: {
                fontCss: getFont,
                nameIsHTML: true,
                showLine: false
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: 0
                }
            },
            callback: {
                onClick: zTreeOnClick
            }
        };

        function getFont(treeId, node) {
            return node.isSys?{"color": "red"}:{};
        }

        var showTree = function (data) {
            $.get(ctx + "/category/tree", data, function (res) {
                if (res.code == 0) {
                    zt = $.fn.zTree.init($("#zTree"), setting, res.data);
                    var nodes = zt.getNodes();
                    for (var i = 0; i < nodes.length; i++) {
                        //设置默认展开二级节点
                        zt.expandNode(nodes[i], true, false, true);
                    }
                    //加载
                    $.each(res.data, function (i, obj) {
                        if(i == 0) $("input#model").val(obj.model);
                        $("select#selPid").append('<option id="pid_' + obj.id + '" model="'+obj.model+'" value="' + obj.id + '">' + obj.name + '</option>');
                    });
                } else {
                    app.tips(res.message, 0);
                }
            });

        }

        function renderTable(pid) {
            layui.table.render({
                elem: '#cate-list'
                , url: ctx + '/category/list?pid=' + pid
                , cols: [[
                    {field: 'catId', width: 80, title: 'ID'}
                    , {field: 'appIcon', width: 100, title: '手机图标', align: 'center', templet: '#appIconBar'}
                    , {field: 'webIcon', width: 100, title: 'Web图标', align: 'center', templet: '#webIconBar'}
                    , {field: 'catName', width: 150, title: '分类名称', edit: 'text'}
                    , {field: 'linkUrl', title: '链接地址', edit: 'text'}
                    , {field: 'sort', width: 80, title: '排序', edit: 'text'}
                    , {field: 'hits', width: 80, title: '点击数'}
                    , {field: 'isView', width: 80, title: '状态', templet: '#checkBar'}
                    , {field: 'action', width: 150, title: '操作', toolbar: '#actBar'}
                ]],
                response: {
                    msgName: 'message' //状态信息的字段名称，默认：msg
                }
            });
        }

        renderTable(0);

        //修改表格内文本字段
        layui.table.on('edit(cate-list-blur)', function (obj) {
            var value = obj.value //得到修改后的值
                , d = obj.data //得到所在行所有键值
                , field = obj.field; //得到字段
            var data = null, tips = null;
            if (field == 'catName') {
                data = {catId: d.catId, catName: value};
                tips = '分类名称修改成功!';
            } else if (field == 'linkUrl') {
                data = {catId: d.catId, linkUrl: value};
                tips = '分类LinkUrl修改成功!';
            } else if (field == 'sort') {
                data = {catId: d.catId, sort: value};
                tips = '分类排序修改成功!';
            }

            if (data != null) {
                $.post(ctx + "/category/update", data, function (res) {
                    if (res.code == 0) {
                        app.tips(tips);
                    } else {
                        app.tips(res.message, 0);
                    }
                });
            }
        });

        //修改分类是否显示隐藏
        layui.form.on('switch(viewCheck)', function (obj) {
            var catName = $(this).attr("cate");
            var chk = this.checked;
            $.post(ctx + "/category/update", {catId: this.value, isView: (chk ? 1 : 0)}, function (res) {
                if (res.code == 0) {
                    app.tips(chk ? "\"" + catName + "\" 已取消隐藏!" : "\"" + catName + "\" 已被隐藏!");
                } else {
                    app.tips(res.message, 0);
                }
            });
        });

        //添加或编辑分类
        $(document).off("click").on("click", ".cate-add, a#edit-cate", function () {
            var optName = "添加";
            var opt = $(this).attr("option");
            var catId;
            //编辑操作
            if (opt == 1) {
                optName = "编辑";
                catId = $(this).attr("data");
                $.get(ctx + "/category/query/"+catId, function(res){
                    if (res.code == 0) {
                        app.fullForm($("form.layui-form"), res.data);
                        if(res.data.isView == 0){
                            $("div.layui-layer div.layui-form-switch").removeClass("layui-form-onswitch");
                            $("div.layui-layer div.layui-form-switch").find("em").text("隐藏");
                        }else{
                            $("div.layui-layer div.layui-form-switch").addClass("layui-form-onswitch");
                            $("div.layui-layer div.layui-form-switch").find("em").text("显示");
                        }
                    } else {
                        app.tips(res.message, 0);
                    }
                });
            }
            var node = zt.getSelectedNodes();
            if (node.length > 0) {
                $("select#selPid option").removeAttr("selected");
                $("select#selPid option#pid_" + node[0].id).attr("selected", "selected");
            }
            //自定页
            layer.open({
                type: 1,
                resize: false,
                title: '<img src="static/icon/create.svg"/> ' + optName + '分类',
                btn: ['Ok', 'Cancel'],
                content: $('#category-box').html(),
                yes: function (index) {
                    var jsonObj = app.serializeObject($("form.layui-form"));
                    if($.trim(jsonObj.catName).length == 0){
                        app.tips("请输入分类名称!", 0);
                        return;
                    }
                    else if (!/^[0-9]*$/.test(jsonObj.sort)) {
                        app.tips("排序只能输入正整数!", 0);
                        return;
                    }
                    jsonObj.isView = $("div.layui-layer input#isView").val();
                    var node = zt.getNodeByParam("id", jsonObj.parentId);
                    jsonObj.level = node ? node.level : 0;

                    var url = opt == 1 ? ctx + "/category/update" : ctx + "/category/create";
                    if(opt ==1){
                        jsonObj.catId = catId;
                    }
                    $.post(url, jsonObj, function (res) {
                        if (res.code == 0) {
                            app.tips(opt ==1 ? "菜单修改成功!" : "新菜单创建成功!");
                            layer.closeAll();
                            //刷新树
                            showTree({pId: 0});
                            //刷新表格
                            if (lastNode) {
                                renderTable(lastNode.id);
                            } else {
                                renderTable(0);
                            }
                        } else {
                            app.tips(res.message, 0);
                        }
                    });
                }
            });
            layui.form.render(null, 'category'); //更新全部;

            //上传图标
            var uploadInst = layui.upload.render({
                elem: "div.layui-layer #iconUpload" //绑定元素
                , url: ctx + '/upload/oss' //上传接口
                , data: {dir: "IdleEgg/icon/cate"}
                , exts: "png|svg"
                , field: "files"
                , size: 1000
                , done: function (res) {
                    //上传完毕回调
                    if (res.code == 0) {
                        var i = this.item.attr("index");
                        //上传appIcon
                        if (i == 0) {
                            app.tips("App分类图标上传成功!");
                            $("input#appIcon").val(res.data[0]);
                        }
                        //上传webIcon
                        else if (i == 1) {
                            app.tips("Pc分类图标上传成功!");
                            $("input#webIcon").val(res.data[0]);
                        }
                    } else {
                        app.tips(res.message, 0);
                    }
                }
            });
        });

        //修改分类是否显示隐藏
        layui.form.on('switch(isViewCheck)', function (obj) {
            this.value = this.checked ? 1 : 0;
        });

        //删除分类
        $(document).on("click", "a#del-cate", function () {
            var _that = $(this);
            var catName = _that.attr("cate");
            layer.confirm("是否确定删除 \"" + catName + "\"？", {
                btn: ['Ok', 'Cancel'] //按钮
            }, function (index) {
                var catId = _that.attr("data");
                $.post(ctx + "/category/delete/" + catId, function (res) {
                    if (res.code == 0) {
                        app.tips("\"" + catName + "\" 删除成功!");
                        layer.closeAll();
                        //刷新树
                        showTree({pId: 0});
                        //刷新表格
                        if (lastNode) {
                            renderTable(lastNode.id);
                        } else {
                            renderTable(0);
                        }
                    } else {
                        app.tips(res.message, 0);
                    }
                });
            });
        });

        $(document).on("click", "span.cate-parent", function () {
            renderTable(0);
            zt.cancelSelectedNode();
        });

        //第一次加载树
        showTree({pId: 0});

        //刷新菜单
        $(document).on("click", "span.cate-refresh", function () {
            showTree({pId: 0});
        });

        //监听下拉框
        layui.form.on('select(selClick)', function(data){
            var model = $(data.elem).find("#pid_"+data.value).attr("model");
            $("input#model").val(model);
        });

    });
</script>